package com.findu.control;

import java.util.Iterator;
import java.util.List;

import android.app.ActivityManager;
import android.app.Application;
import android.content.pm.PackageManager;
import android.util.Log;

import cn.ciaapp.sdk.CIAService;

import com.easemob.chat.EMChat;

public class FUApplication extends Application {
	 // TODO
    protected static final String appId = "d1dfed101822495c846d15dea7344f8c";
    protected static final String authKey = "b695e211ae0d4cce97d9957c373f18ed";

	@Override
	public void onCreate() {
		 
		super.onCreate();
	    // TODO 初始化CIA服务，填写申请的appId和authKey
        CIAService.init(this, appId, authKey);
		
		int pid = android.os.Process.myPid();
		String processAppName = getAppName(pid);
		if (processAppName == null ||!processAppName.equalsIgnoreCase("com.example.findu")) {
		    Log.e("FindU", "enter the service process!");
		    //"com.easemob.chatuidemo"为demo的包名，换到自己项目中要改成自己包名
		 
		    // 则此application::onCreate 是被service 调用的，直接返回
		    return;
		}
		EMChat.getInstance().init(getApplicationContext());
		EMChat.getInstance().setDebugMode(true);
	}

	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		super.onTerminate();
	}

	private String getAppName(int pID) {
		String processName = null;
		ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
		List l = am.getRunningAppProcesses();
		Iterator i = l.iterator();
		PackageManager pm = this.getPackageManager();
		while (i.hasNext()) {
			ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
			try {
				if (info.pid == pID) {
					CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
					// Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
					// info.processName +"  Label: "+c.toString());
					// processName = c.toString();
					processName = info.processName;
					return processName;
				}
			} catch (Exception e) {
				// Log.d("Process", "Error>> :"+ e.toString());
			}
		}
		return processName;
	}
}
